<?php

namespace app\common\library\wechat;

use app\common\model\Wxapp as WxappModel;
use think\Cache;
use think\Exception;
use think\Log;

class WxClient
{
    private $config; // 微信配置

    /**
     * 构造方法
     * WxPay constructor.
     * @param $config
     */
    public function __construct()
    {
        $this->config = WxappModel::getWxappCache('10001');
    }

    public function getAccessToken()
    {
        if (!$access_token_str = Cache::get('access_token')) {
            Log::record("access_token缓存不存在");
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->config['app_id'] . "&secret=" . $this->config['app_secret'];
            $access_token = file_get_contents($url);
            Log::record("access token result --> " . $access_token);
            $access_token_arr = json_decode($access_token, true);
            if (isset($access_token_arr['errcode'])) {
                Log::record("微信API接口调用次数达到上限");
                return null;
            }
            $access_token_str = $access_token_arr['access_token'];
            Cache::set('access_token', $access_token_str, $access_token_arr['expires_in']);
        }
        Log::record("access token result --> " . $access_token_str);
        return $access_token_str;
    }

    /**
     * 调用微信生成小程序码API
     * @param $page string 扫描小程序码跳转地址
     * @param $scene string 地址带的参数
     * @param $is_hyaline boolean 小程序码背景设置透明
     * @return mixed 图片数据
     */
    public function getQrcode($page, $scene = '', $is_hyaline = true)
    {
        $access_token = $this->getAccessToken();
        //调用微信生成小程序码API
        $new_url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $data = [
            'page' => $page,
            'scene' => $scene,
            'is_hyaline' => false,
            'width' => 280
        ];
        return $this->httpRequest($new_url, $data, "POST");
    }

    private function httpRequest($url, $data = '', $method = 'GET')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
//        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public function sendMessage($data, $touser, $template_id, $page, $miniprogram_state = "formal")
    {
        $access_token = $this->getAccessToken();
        $api = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$access_token";
        $params = [
            'touser' => $touser,
            'template_id' => $template_id,
            'page' => $page,
            'miniprogram_state' => $miniprogram_state,
            'lang' => 'zh_CN',
            'data' => $data
        ];
        Log::record("给用户发送微信消息参数：" . json_encode($params));
        $result = $this->httpRequest($api, $params, 'POST');
        Log::record("发送微信消息返回结果：" . $result);
    }
}
